package com.lipi.mall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.lipi.common.constant.AuthServerConstant;
import com.lipi.common.exception.BizCodeEnum;
import com.lipi.common.utils.R;
import com.lipi.common.vo.MemberRespVO;
import com.lipi.mall.authserver.feign.MemberFeignService;
import com.lipi.mall.authserver.feign.ThirdPartyService;
import com.lipi.mall.authserver.vo.UserLoginVO;
import com.lipi.mall.authserver.vo.UserRegistVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class loginController {


    @GetMapping("/login.html")
    public String login(HttpSession session) {
        //判断用户是否已登录
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);

        if (attribute == null) {
            //未登录
            return "login";
        } else {
            //已登录,跳转首页
            return "redirect:http://mall.com";
        }


    }

    @GetMapping("/reg.html")
    public String reg() {
        return "reg";
    }

    @Autowired
    private ThirdPartyService thirdPartyService;


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 调用三方服务发送验证码
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {

        //1、接口防刷：判断当前号码是否在60s内发送过验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //用户在60s内重复点击了发送验证码,不再发送
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION);
            }

        }

        String code = UUID.randomUUID().toString().substring(0, 5);

        //redis缓存验证码
        redisTemplate.opsForValue().set(
                AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone,
                code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);

        thirdPartyService.sendCode(phone, code);
        return R.ok().put("data", code);
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVO vo,
                         BindingResult result,
                         RedirectAttributes redirectAttributes) {

        //校验数据格式
        if (result.hasErrors()) {
            //参数格式校验失败
            Map<String, String> errors = result.getFieldErrors().stream().collect(
                    Collectors.toMap(FieldError::getField,
                            FieldError::getDefaultMessage,
                            //若key相同,覆盖
                            (entity1, entity2) -> entity1));

//            model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
        //校验验证码
        String fullCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isEmpty(fullCode)) {
            //验证码校验错误
            Map<String, String> errors = new HashMap<>();
            //显示在验证码框上方
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
        String code = fullCode.split("_")[0];
        if (StringUtils.isEmpty(code) || !code.equalsIgnoreCase(vo.getCode())) {

            //验证码校验错误
            Map<String, String> errors = new HashMap<>();
            //显示在验证码框上方
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
        //令牌机制：验证通过,删除验证码
        redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        //调用用户服务,注册用户
        R r = memberFeignService.regist(vo);
        if (r.getCode() != 0) {
            Map<String, String> errors = new HashMap<>();
            errors.put("message", r.getMessage(new TypeReference<String>() {
            }));

            redirectAttributes.addFlashAttribute("errors", errors);
            //调用服务失败
            return "redirect:http://auth.mall.com/reg.html";
        }
        //注册成功回到登录页面
        return "redirect:http://auth.mall.com/login.html";
    }


    @PostMapping("/login")
    public String login(UserLoginVO vo,
                        RedirectAttributes redirectAttributes,
                        HttpSession session) {

        //feign会自动将bean转发为实体类
        R r = memberFeignService.login(vo);
        if (r.getCode() != 0) {
            //登录失败逻辑
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getMessage(new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/login.html";
        }
        //登录成功逻辑
        //获取用户信息,并保存至session
        MemberRespVO data = r.getData(new TypeReference<MemberRespVO>() {
        });
        session.setAttribute(AuthServerConstant.LOGIN_USER, data);

        //跳转首页
        return "redirect:http://mall.com";
    }
}
